package com.ruoyi.employee.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.employee.domain.EmployeeStatic;
import com.ruoyi.employee.mapper.*;
import com.ruoyi.market.domain.ConfigEmployee;
import com.ruoyi.market.domain.Level;
import com.ruoyi.market.service.IConfigEmployeeService;
import com.ruoyi.market.service.ILevelService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.service.IEmployeeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店员 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class EmployeeUserServiceImpl implements IEmployeeUserService
{

    @Autowired
    private EmployeeUserMapper userMapper;

    @Autowired
    private EmployeeStaticMapper employeeStaticMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IConfigEmployeeService configEmployeeService;

    @Autowired
    private ILevelService levelService;

    @Autowired
    protected Validator validator;

    /**
     * 根据条件分页查询店员列表
     * 
     * @param user 店员信息
     * @return 店员信息集合信息
     */
    @Override
    // @DataScope(deptAlias = "d", userAlias = "u")
    public List<EmployeeUser> selectUserList(EmployeeUser user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 通过店员名查询店员
     * 
     * @param userName 店员名
     * @return 店员对象信息
     */
    @Override
    public EmployeeUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过店员ID查询店员
     * 
     * @param userId 店员ID
     * @return 店员对象信息
     */
    @Override
    public EmployeeUser selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }

    /**
     * 校验店员名称是否唯一
     * 
     * @param user 店员信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(EmployeeUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验店员昵称是否唯一
     *
     * @param user 店员信息
     * @return 结果
     */
    @Override
    public boolean checkNickNameUnique(EmployeeUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeUser info = userMapper.checkNickNameUnique(user.getNickName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 店员信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(EmployeeUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一 通过手机号
     *
     * @param userId 店员信息
     * @return
     */
    @Override
    public boolean checkPhoneUniqueByPhone(Long userId, String phone)
    {
        EmployeeUser info = userMapper.checkPhoneUnique(phone);
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 店员信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(EmployeeUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 店员信息
     * @return
     */
    @Override
    public boolean checkWxIdUnique(EmployeeUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        EmployeeUser info = userMapper.checkWxIdUnique(user.getWxId());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验店员是否允许操作
     * 
     * @param user 店员信息
     */
    @Override
    public void checkUserAllowed(EmployeeUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员店员");
        }
    }

    /**
     * 校验店员是否有数据权限
     *
     * @param userId 店员id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
        if (!EmployeeUser.isAdmin(SecurityUtils.getUserId()))
        {
            EmployeeUser user = new EmployeeUser();
            user.setUserId(userId);
            List<EmployeeUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问店员数据！");
            }
        }
    }

    /**
     * 新增保存店员信息
     * 
     * @param user 店员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(EmployeeUser user)
    {
        // 新增店员信息
        int rows = userMapper.insertUser(user);

        // 统计表新增用户
        EmployeeStatic employeeStatic = new EmployeeStatic();
        employeeStatic.setUserId(user.getUserId());
        employeeStatic.setShopId(user.getShopId());
        employeeStaticMapper.insertUser(employeeStatic);

        return rows;
    }

    /**
     * 修改保存店员信息
     * 
     * @param user 店员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(EmployeeUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改保存店员信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateUserLevel()
    {
        EmployeeUser user = new EmployeeUser();
        Level level = new Level();
        // 店员列表
        List<EmployeeUser> userList = userMapper.selectUserList(user);
        for(EmployeeUser e : userList){
            level.setShopId(e.getShopId());

            // 查询店员近7天的总收益
            BigDecimal totalAmount = userMapper.selectTotalAmountInSevenDay(e.getUserId());

            // 查询店员当前等级信息
            Level currentLevelInfo = levelService.selectLevelById(e.getUserLevel());

            Map<String, Object> map = new HashMap<>();
            // 收益变高 并且 查询到还有升级空间
            if(currentLevelInfo.getAdvanceAmount().compareTo(totalAmount) < 0){
                map.put("advanceAmount", currentLevelInfo.getAdvanceAmount());
                level.setParams(map);
                // 店铺配置的等级列表 要求大于最近7天的总收益
                List<Level> levelList_advance = levelService.selectLevelList(level);
                if(!levelList_advance.isEmpty()){
                    for(Level l : levelList_advance){
                        if(l.getAdvanceAmount().compareTo(totalAmount) <= 0){
                            e.setUserLevel(l.getLevelId());
                            userMapper.updateUser(e);
                            break;
                        }
                    }
                }
            }
            // 收益降低
            if(currentLevelInfo.getAdvanceAmount().compareTo(totalAmount) > 0){
                // 店员信息
                ConfigEmployee configEmployee = configEmployeeService.selectConfigEmployeeByShopId(e.getShopId());
                if(configEmployee.getStatusReduceLevel().equals(UserConstants.YES)){
                    // 开启了降级
                    map.put("reduceAmount", totalAmount);
                    level.setParams(map);
                    // 店铺配置的等级列表 要求大于最近7天的总收益
                    List<Level> levelList_reduce = levelService.selectLevelList(level);
                    if(!levelList_reduce.isEmpty()){
                        // 开启降级
                        for(Level l : levelList_reduce){
                            if(l.getAdvanceAmount().compareTo(totalAmount) <= 0){
                                e.setUserLevel(l.getLevelId());
                                userMapper.updateUser(e);
                                break;
                            }
                        }
                    }
                }
            }

        }

    }

    /**
     * 修改保存店员信息 - 评分
     *
     * @param userId 店员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUserScore(Long userId, Double score)
    {
        EmployeeUser user = userMapper.selectUserById(userId);
        user.setScore(score);
        return userMapper.updateUser(user);
    }

    /**
     * 修改店员状态
     * 
     * @param user 店员信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(EmployeeUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改店员基本信息
     * 
     * @param user 店员信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(EmployeeUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改店员头像
     * 
     * @param userName 店员名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置店员密码
     * 
     * @param user 店员信息
     * @return 结果
     */
    @Override
    public int resetPwd(EmployeeUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 重置店员密码
     * 
     * @param userName 店员名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 通过店员ID删除店员
     * 
     * @param userId 店员ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId)
    {
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除店员信息
     * 
     * @param userIds 需要删除的店员ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new EmployeeUser(userId));
            checkUserDataScope(userId);
        }
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入店员数据
     * 
     * @param userList 店员数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作店员
     * @return 结果
     */
    @Override
    public String importUser(List<EmployeeUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入店员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (EmployeeUser user : userList)
        {
            try
            {
                // 验证是否存在这个店员
                EmployeeUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
